// pages/my/my.js

import { ClassicModel } from '../../models/ClassicModel'
import { BookModel } from '../../models/BookModel'
import { promisic, promisic2 } from '../../utils/common'

const classicModel = new ClassicModel()
const bookModel = new BookModel()
Page({

    /**
   * 页面的初始数据
   */
    data: {
        authorized: false,
        userInfo: null,
        classics: null,
        bookCount: 0

    },

    onShow () {
        this.getMyBookCount()
        this.getMyFavor()
        this.userAuthorized2()
    },

    userAuthorized2 () {
        promisic2(wx.getSetting)
            .then(res => {
                if (res.authSetting['scope.userInfo']) {
                    return promisic2(wx.getUserInfo)
                }
                return false
            })
            .then(data => {
                if (!data) return
                this.setData({
                    authorized: true,
                    userInfo: data.userInfo
                })
            })
    },

    userAuthorized () {
        wx.getSetting({
            success: data => {
                if (data.authSetting['scope.userInfo']) {
                    wx.getUserInfo({
                        success: data => {
                            this.setData({
                                authorized: true,
                                userInfo: data.userInfo
                            })
                        }
                    })
                }
            }
        })
    },

    getMyFavor () {
        classicModel.getMyFavor(res => {
            this.setData({
                classics: res
            })
        })
    },

    getMyBookCount () {
        bookModel.getMyBookCount()
            .then(res => {
                this.setData({
                    bookCount: res.data.count
                })
            })
    },

    onGetUserInfo (event) {
        const userInfo = event.detail.userInfo
        if (userInfo) {
            this.setData({
                userInfo,
                authorized: true
            })
        }
    },

    onStudy () {
        wx.navigateTo({
            url: '/pages/course/course'
        })
    },

    onJumpToDetail (event) {
        const cid = event.detail.cid
        const type = event.detail.type
        wx.navigateTo({
            url: `/pages/classic-detail/classic-detail?cid=${cid}&type=${type}`
        })
    }
})
